const basePage = require('../../../common/BasePage')
Page({
  behaviors: [basePage],
  data: {
    searchValue: '',
    catArr1: [],
    catIdx1: 0,
    catArr2: [],
    catArr3: [],
    catIdx2: 0,
    catIdx3: 0,
    dataArr: [],
    storeSid: '',
    /**购物车数据 */
    cartObj: {},
    /**购物车总数量 */
    cartNum: 0,
    store: {},
    firstLevelSid: "",
    secondLevelSid: "",
    thirdLevelSid: "",
    /**指定置顶商品 */
    goods: {}
  },

  onShow() {
    let storeSid = this.data.storeSid
    //第二次进入页面，刷新购物车数量
    if (this.data.catArr2 && this.data.catArr2.length > 0) {
      this.request({
        url: this.data.host + "/v1/carts/me",
        data: {
          size: 50,
          latitude: this.data.latitude,
          longitude: this.data.longitude,
        },
      }, res => {
        // console.log('购物车', res);
        let obj = {};
        let cartNum = 0;
        res.data.records.map(val => {
          val.goods.map(good => {
            cartNum += good.number * 1;
            if (good.storeSid == storeSid) {
              obj[good.goodsSid] = {
                storeSid: good.storeSid,
                number: good.number,
                stock: good.stock,
                cartSid: good.sid
              }
            }
          })
        });
        //更新置顶商品的购物车
        let val = this.data.goods;
        if (val && val.sid && obj[val.sid]) {
          let good = obj[val.sid];
          val.storeSid = good.storeSid;
          val.number = good.number;
          val.stock = good.stock;
          val.cartSid = good.cartSid;
          this.setData({
            goods: val,
            cartObj: obj,
            cartNum: cartNum
          })
        } else {
          this.setData({
            cartObj: obj,
            cartNum: cartNum
          })
        }

        wx.setStorage({
          key: 'cartNum',
          data: cartNum
        })
        //刷新商品中的购物车数量
        this.data.dataArr.map(val => {
          if (obj[val.sid]) {
            let good = obj[val.sid];

            val.storeSid = good.storeSid;
            val.number = good.number;
            val.stock = good.stock;
            val.cartSid = good.cartSid
          } else {
            val.storeSid = "";
            val.number = 0;
            val.stock = 999;
          }
        })
        this.setData({
          dataArr: this.data.dataArr
        })
      })
    }
  },
  onLoad(obj) {
    //指定跳转商品和其分类

    if (obj.firstLevelSid) {
      let goods = wx.getStorageSync('goods')
      if (goods) {
        this.setData({
          goods: {
            sid: goods.goodsSid || goods.sid,
            thumb: goods.thumb,
            goodsName: goods.goodsName,
            points: goods.integral || goods.points,
            price: goods.price,
            stock: goods.stock || 999,
            number: 0,
            thirdLevelSid: goods.thirdLevelSid
          },
          firstLevelSid: goods.firstLevelSid,
          secondLevelSid: goods.secondLevelSid,
          thirdLevelSid: goods.thirdLevelSid
        })
      }
    }
    this.setData({
      catIdx1: obj.index || 0,
      storeSid: obj.storeSid || '',
      store: wx.getStorageSync('store')
    })
    let storeSid = obj.storeSid;
    let globalData = getApp().globalData;
    this.data.latitude = globalData.latitude;
    this.data.longitude = globalData.longitude
    this.request({
      url: this.data.host + "/v1/carts/me",
      data: {
        size: 50,
        latitude: this.data.latitude,
        longitude: this.data.longitude,
      },
    }, res => {
      // console.log('购物车', res);
      let obj = {};
      let cartNum = 0;
      res.data.records.map(val => {
        val.goods.map(good => {
          cartNum += good.number * 1;
          if (good.storeSid == storeSid) {
            obj[good.goodsSid] = {
              storeSid: good.storeSid,
              number: good.number,
              stock: good.stock,
              cartSid: good.sid
            }
          }
        })
      });
      //更新置顶商品的购物车
      let val = this.data.goods;
      if (val && val.sid && obj[val.sid]) {
        let good = obj[val.sid];
        val.storeSid = good.storeSid;
        val.number = good.number;
        val.stock = good.stock;
        val.cartSid = good.cartSid;
        this.setData({
          goods: val,
          cartObj: obj,
          cartNum: cartNum
        })
      } else {
        this.setData({
          cartObj: obj,
          cartNum: cartNum
        })
      }
      // console.log('购物车1', obj);
      wx.setStorage({
        key: 'cartNum',
        data: cartNum
      })
    })

    //获取一级分类
    this.request({
      url: this.data.host + '/v1/categories/program',
    }, res => {
      this.setData({
        catArr1: res.data
      })
      //更新当前选中的分类索引
      if (this.data.firstLevelSid) {
        this.data.catIdx1 = this.update_catIdx(this.data.firstLevelSid, res.data)
      }

      this.req_cat2();
    })
  },
  search_click() {
    let userInfo = getApp().globalData.userInfo;
    let searchUrl = '/pages/goods/find';
    if (this.data.storeSid) {
      searchUrl = '/pages/store/search/index';
    }
    // console.log('search_click', userInfo);
    if (!userInfo || !userInfo.cardNumber) {
      this.request({
        url: this.data.host + "/v1/users/me"
      }, res => {
        // console.log("/v1/users/me", res);
        getApp().globalData.userInfo = res.data;
        if (res.data.cardNumber) {
          wx.navigateTo({
            url: searchUrl
          });
        } else {
          wx.showModal({
            showCancel: true,
            title: '提示',
            content: "需实名认证才可以使用该功能哦",
            confirmColor: "#23BC97",
            success: (result) => {
              if (result.confirm) {
                wx.redirectTo({
                  url: '/pages/usercenter/identity',
                })
              }
            },

          })
        }
      })

    } else {
      wx.navigateTo({
        url: searchUrl
      });
    }
  },
  kf_click() {
    wx.openCustomerServiceChat({
      corpId: 'ww72ede85652b45a26',
      extInfo: {
        url: this.data.store.customerUrl,
      },
      success: (res) => {
        console.log('打开成功', res);
      },
      fail: (res) => {
        console.log('打开失败', res);
        wx.showToast({
          title: '打开失败',
          icon: 'error'
        })
      },
    })
  },
  location_click() {
    wx.openLocation({
      latitude: this.data.store.latitude * 1,
      longitude: this.data.store.longitude * 1,

      fail: (res) => {
        wx.showToast({
          title: JSON.stringify(res),
        })
      },
      complete: (res) => {},
    })
  },
  cat1_change(e) {
    // console.log("cat1_change", e);
    if (e.currentTarget.dataset.index == this.data.catIdx1) {
      return;
    }
    this.setData({
      goods: {},
      catIdx1: e.currentTarget.dataset.index,
      catIdx2: 0,
      catIdx3: 0
    })
    this.req_cat2()
  },
  update_catIdx(sid, arr) {
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].sid == sid) {
        return i;
      }
    }
    return;
  },
  req_cat2() {
    this.request({
      url: this.data.host + '/v1/categories/program',
      data: {
        parentSid: this.data.catArr1[this.data.catIdx1].sid
      }
    }, res => {
      this.setData({
        catIdx1: this.data.catIdx1,
        catArr2: res.data
      })
      if (this.data.secondLevelSid) {
        this.data.catIdx2 = this.update_catIdx(this.data.secondLevelSid, res.data);
        this.data.secondLevelSid = ""
      }
      this.req_cat3();
    })
  },
  req_cat3() {
    this.request({
      url: this.data.host + '/v1/categories/program',
      data: {
        parentSid: this.data.catArr2[this.data.catIdx2].sid
      }
    }, res => {
      this.setData({
        catIdx2: this.data.catIdx2,
        catArr3: res.data
      })
      if (this.data.thirdLevelSid) {
        this.setData({
          catIdx3: this.update_catIdx(this.data.thirdLevelSid, res.data)
        })

        this.data.thirdLevelSid = ""
      }
      this.req_list()
    })
  },
  req_list() {
    this.request({
      url: this.data.host + "/v1/categories/" + this.data.catArr3[this.data.catIdx3].sid + "/goods",
      data: {
        categorySid: this.data.catArr3[this.data.catIdx3].sid,
        goodsName: this.data.searchValue,
        publishState: 2,
        storeSid: this.data.storeSid,
        levelCategorySid: this.data.catArr1[this.data.catIdx1].sid,
        size: 50
      }
    }, res => {
      // console.log('商品', res);
      res.data.records.map(val => {
        val.thumb = this.get_imgUrl(val.goodsImg);
        let obj = this.data.cartObj;
        if (obj[val.sid]) {
          let good = obj[val.sid];

          val.storeSid = good.storeSid;
          val.number = good.number;
          val.stock = good.stock;
          val.cartSid = good.cartSid
        } else {
          val.storeSid = "";
          val.number = 0;
          val.stock = 999;
        }
      })
      this.setData({
        dataArr: res.data.records
      })
    })
  },

  add_cart(e) {
    console.log('add', e.currentTarget.dataset.item);
    let item = e.currentTarget.dataset.item;
    let i = e.currentTarget.dataset.index;
    let that = this;
    if (this.data.storeSid) {
      return this.req_add_cart(this.data.storeSid, item, i)
    } else {
      this.req_store(item, i);
    }
  },
  req_store(item, i) {
    this.request({
      url: this.data.host + '/v1/carts/store/' + item.sid,
      data: {
        latitude: this.data.latitude,
        longitude: this.data.longitude,

      },
      loadingTip: '获取门店'
    }, res => {

      this.req_add_cart(res.data, item, i)
    })
  },
  goods_add() {
    let item = this.data.goods;
    const storeSid = this.data.storeSid;
    this.request({
      url: this.data.host + '/v1/carts/add',
      data: {
        goodsSid: item.sid,
        storeSid: storeSid
      },
      method: 'put',
      loadingTip: '加购...'
    }, res => {

      item.storeSid = storeSid;
      item.number = 1;
      item.cartSid = res.data

      this.setData({
        goods: item,
        cartNum: this.data.cartNum * 1 + 1
      })
      wx.setStorage({
        key: 'cartNum',
        data: this.data.cartNum
      })
    })
  },
  req_add_cart(storeSid, item, i) {
    this.request({
      url: this.data.host + '/v1/carts/add',
      data: {
        goodsSid: item.sid,
        storeSid: storeSid
      },
      method: 'put',
      loadingTip: '加购...'
    }, res => {

      item.storeSid = storeSid;
      item.number = 1;
      item.cartSid = res.data
      this.data.dataArr[i] = item;
      this.setData({
        dataArr: this.data.dataArr,
        cartNum: this.data.cartNum * 1 + 1
      })
      wx.setStorage({
        key: 'cartNum',
        data: this.data.cartNum
      })
    })
  },
  /**置顶商品修改购物车 */
  goods_cart(e) {
    let item = this.data.goods;
    if (e.detail.value == 0) {
      //删除购物车
      this.request({
        url: this.data.host + "/v1/carts/del",
        method: "put",
        data: {
          sidList: [item.cartSid]
        }
      }, res => {
        let num = 0 - item.number;
        item.number = 0;
        this.setData({
          goods: item,
          cartNum: this.data.cartNum + num
        })
        wx.setStorage({
          key: 'cartNum',
          data: this.data.cartNum
        })
      })
    } else {
      //修改购物车数量
      this.request({
        url: this.data.host + "/v1/carts/number",
        method: "put",
        data: {
          number: e.detail.value,
          sid: item.cartSid
        }
      }, res => {
        /**增减数量 */
        let num = e.detail.value - item.number;
        item.number = e.detail.value;
        this.setData({
          goods: item,
          cartNum: this.data.cartNum + num
        })
        wx.setStorage({
          key: 'cartNum',
          data: this.data.cartNum
        })
      })
    }
  },
  cart_change(e) {

    let item = e.currentTarget.dataset.item;
    let i = e.currentTarget.dataset.index;
    if (e.detail.value == 0) {
      //删除购物车
      this.request({
        url: this.data.host + "/v1/carts/del",
        method: "put",
        data: {
          sidList: [item.cartSid]
        }
      }, res => {
        let num = e.detail.value - this.data.dataArr[i].number;
        this.data.dataArr[i].number = e.detail.value;
        this.setData({
          dataArr: this.data.dataArr,
          cartNum: this.data.cartNum + num
        })
        wx.setStorage({
          key: 'cartNum',
          data: this.data.cartNum
        })
      })
    } else {
      //修改购物车数量
      this.request({
        url: this.data.host + "/v1/carts/number",
        method: "put",
        data: {
          number: e.detail.value,
          sid: item.cartSid
        }
      }, res => {
        /**增减数量 */
        let num = e.detail.value - this.data.dataArr[i].number;
        this.data.dataArr[i].number = e.detail.value;
        this.setData({
          dataArr: this.data.dataArr,
          cartNum: this.data.cartNum + num
        })
        wx.setStorage({
          key: 'cartNum',
          data: this.data.cartNum
        })
      })
    }
  },
  cat2_change(e) {
    if (e.currentTarget.dataset.index == this.data.catIdx3) {
      return;
    }
    this.setData({
      // catIdx2: e.currentTarget.dataset.index,
      catIdx3: e.currentTarget.dataset.index,
      goods: {}
    })
    // this.req_cat3()
    this.req_list()
  },
  /**二级 */
  onSideBarChange(e) {

    if (this.data.catIdx2 == e.detail.value) {
      return;
    }
    this.setData({
      goods: {},
      catIdx2: e.detail.value,
      catIdx3: 0
    })
    this.req_cat3()
    // this.req_list()
  },
  handleSubmit(e) {

    // console.log('handleSubmit', e);
    // console.log('searche', this.data.searchValue);
    this.data.searchValue = e.detail.value;
    this.req_list()
  },
});